package com.crazypos.service.impl;

import com.crazypos.config.UploadConfig;
import com.crazypos.constant.UploadTypeConstant;
import com.crazypos.service.IUploadImageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.UUID;

@Service
@Slf4j
public class UploadImageService implements IUploadImageService {

    @Override
    public String uploadImage(MultipartFile file, String imageType, String filepath) throws IOException {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("文件的后缀名为：" + suffixName);

        String date = new SimpleDateFormat("yyyyMMdd").format(System.currentTimeMillis());
        String targetDir = UploadConfig.assetRootDir + imageType + "/" + filepath;

        //获得图片名称
        String photoName = date + System.currentTimeMillis() + suffixName;

        log.info("图片被上传到了：{}", targetDir + photoName);

        String fileurl = targetDir + "/" + photoName;

        File targetFile = new File(fileurl);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        file.transferTo(targetFile);

        return fileurl;
    }
}
